import gtk, gtk.glade
import md5
from NetlogMusicConf import NetlogMusicConf
from NetlogCommunicator import NetlogCommunicator

class NetlogConfDialog(object):
	def __init__(self, gladef, config, comm):
		self.glade = gtk.glade.XML(gladef)
		self.config = config
		self.comm = comm
		self.config_dialog = self.glade.get_widget("window")
		self.loginmode = not self.comm.isLoggedIn()
				
		self.username = self.glade.get_widget("user")
		self.password = self.glade.get_widget("pw")
		self.domain = self.glade.get_widget("domain")
		self.autologin = self.glade.get_widget("auto-login")
		self.button = self.glade.get_widget("button1")
		
		self.username.set_text(self.config.get("username"))
		self.domain.set_text(self.config.get("domain"))
		self.autologin.set_active(self.config.get_bool("autologin"))
		
		self.button.connect("clicked",self.dialog_login)		
		self.set_layout(not self.loginmode)
		
	def get_dialog(self):
		return self.config_dialog
		
	def set_layout(self, loggedin):
		if loggedin:
			self.username.set_editable(False)
			self.password.set_editable(False)
			self.domain.set_editable(False)
			self.button.set_label("Logout")
		else:
			self.username.set_editable(True)
			self.password.set_editable(True)
			self.domain.set_editable(True)
			self.button.set_label("Login")
	
		
	def dialog_login(self, dialog):
		self.config.set("username", self.username.get_text())
		self.config.set("domain", self.domain.get_text())
		self.config.set_bool("autologin",self.autologin.get_active())
		pw = self.password.get_text()
		if pw is not "":
			self.config.set("password", md5.new(pw).hexdigest())
		
		
		if self.loginmode:
			self.comm.update_settings(True)
			if self.comm.isLoggedIn():
				self.loginmode = False
		else:
			self.comm.logout()
			self.loginmode = True
		
		self.set_layout(not self.loginmode)
	
